package com.monas.client.jfree;

import java.awt.Color;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.time.Minute;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.RectangleInsets;

public class MonasTimeLineChart extends AbstractMonasChart {

	public MonasTimeLineChart(String title, String xLabel, String yLabel) {
		super(title, xLabel, yLabel);
		dataSet = new TimeSeriesCollection();
	}

	@Override
	public void createChart() {
		chart = ChartFactory.createTimeSeriesChart(title, // title
				xLabel, // x-axis label
				yLabel, // y-axis label
				(TimeSeriesCollection) dataSet, // data
				true, // create legend?
				true, // generate tooltips?
				false // generate URLs?
				);

		chart.setBackgroundPaint(Color.white);

		XYPlot plot = (XYPlot) chart.getPlot();
		plot.setBackgroundPaint(Color.lightGray);
		plot.setDomainGridlinePaint(Color.white);
		plot.setRangeGridlinePaint(Color.white);
		plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
		plot.setDomainCrosshairVisible(true);
		plot.setRangeCrosshairVisible(true);

		XYItemRenderer r = plot.getRenderer();
		if (r instanceof XYLineAndShapeRenderer) {
			XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
			renderer.setBaseShapesVisible(true);
			renderer.setBaseShapesFilled(true);
			renderer.setDrawSeriesLineAsPath(true);
		}

		DateAxis axis = (DateAxis) plot.getDomainAxis();
		axis.setDateFormatOverride(new SimpleDateFormat("yy/MM/dd HH:mm:ss"));
	}

	public void addTimeSeries(String label, List<Timestamp> times,
			List<Number> values) {
		TimeSeries series = new TimeSeries(label);
		for (int i = 0; i < times.size(); i++) {
			Timestamp time = times.get(i);
			series.add(new Minute(time), values.get(i));
		}

		((TimeSeriesCollection) dataSet).addSeries(series);
	}

	@Override
	public void clearData() {
		((TimeSeriesCollection) dataSet).removeAllSeries();
	}

	@Override
	protected int getWidth() {
		return 900;
	}

	@Override
	protected int getHeight() {
		return 300;
	}

}
